
#include "xrj_common_datatype.h"
#include "xrj_mutex_lock.h"


#define  IOT_MQTT_MUTEX_PRIO                 (OS_TASK_TMR_PRIO + 15)
#define	MUXTEX_NUM								15
#define IOT_MQTT_MUTEX_Pri_Start		(OS_TASK_TMR_PRIO+1)
#define IOT_MQTT_MUTEX_Pri_End  		(OS_TASK_TMR_PRIO+MUXTEX_NUM)
static UINT8	tab_Mutux_Prio[MUXTEX_NUM] = {0};

INT32	XRJ_mutex_init (XRJ_IOT_MUTEX_S *mutex );
INT32	XRJ_mutex_lock (XRJ_IOT_MUTEX_S *mutex );
INT32	XRJ_mutex_unlock (XRJ_IOT_MUTEX_S *mutex );
INT32 XRJ_mutex_destory( XRJ_IOT_MUTEX_S *mutex );

INT32 XRJ_mutex_init( XRJ_IOT_MUTEX_S *mutex )
{
    if( mutex == NULL )
    {
        IOT_FUNC_EXIT_RC(ERROR_NULL_VALUE);
    }
	
	UINT8 Err = 0;
	UINT8 i = 0;
	UINT8 t_MutexPri = 0;
	UINT8	t_Index_bak = 0;
	for (i = 0; i < MUXTEX_NUM ;i++)
	{	
		if (tab_Mutux_Prio[i] == 0)
		{
			t_MutexPri = IOT_MQTT_MUTEX_Pri_Start+i;
			t_Index_bak = i;
			break;
		}		
	}			
    if (t_MutexPri == 0)
	{	
		printf("uC/OS-II:create mutex failed: %d\n", Err);
		IOT_FUNC_EXIT_RC(FAIL_RETURN);	
	}
    mutex->osEvent = OSMutexCreate(t_MutexPri, &Err);
		
	if(OS_ERR_NONE != Err)
	{
		printf("uC/OS-II:create mutex failed: %d\n", Err);
		IOT_FUNC_EXIT_RC(FAIL_RETURN);
	}
	tab_Mutux_Prio[t_Index_bak] = 0xff;
	IOT_FUNC_EXIT_RC(SUCCESS_RETURN);

}


INT32 XRJ_mutex_destory( XRJ_IOT_MUTEX_S *mutex )
{
	if( mutex == NULL )
	{
		IOT_FUNC_EXIT_RC(ERROR_NULL_VALUE);
	}

	UINT8 Opt = OS_DEL_NO_PEND;
	UINT8 Err = 0;
	UINT16 t_EventCnt;

	t_EventCnt = (mutex->osEvent->OSEventCnt)>>8;



	OSMutexDel(mutex->osEvent, Opt, &Err);

	if(OS_ERR_NONE != Err)
	{
		printf("uC/OS-II:destory mutex failed: %d\n", Err);
		IOT_FUNC_EXIT_RC(FAIL_RETURN);
	}

	if ((IOT_MQTT_MUTEX_Pri_Start<=t_EventCnt) && (t_EventCnt<=IOT_MQTT_MUTEX_Pri_End))
		tab_Mutux_Prio[t_EventCnt - IOT_MQTT_MUTEX_Pri_Start] = 0x00;
	
	IOT_FUNC_EXIT_RC(SUCCESS_RETURN);
}







INT32	XRJ_mutex_lock (XRJ_IOT_MUTEX_S *mutex )
{
    if( mutex == NULL )
    {
        IOT_FUNC_EXIT_RC(ERROR_NULL_VALUE);
    }
	
	UINT32 Timeout = 0;
    UINT8 Err = 0; 

	/*wait forever*/
    OSMutexPend(mutex->osEvent, Timeout, &Err);

	if(OS_ERR_NONE != Err)
	{
		printf("uC/OS-II:lock mutex failed: %d\n", Err);
		IOT_FUNC_EXIT_RC(FAIL_RETURN);
	}

    IOT_FUNC_EXIT_RC(SUCCESS_RETURN);
}


INT32	XRJ_mutex_unlock (XRJ_IOT_MUTEX_S *mutex )
{
	if( mutex == NULL )
	{
			IOT_FUNC_EXIT_RC(ERROR_NULL_VALUE);
	}

	UINT8 ret = 0;

	ret = OSMutexPost(mutex->osEvent);

	if(OS_ERR_NONE != ret)
	{
		printf("uC/OS-II:unlock mutex failed: %d\n", ret);
		IOT_FUNC_EXIT_RC(FAIL_RETURN);
	}

	IOT_FUNC_EXIT_RC(SUCCESS_RETURN);
}
  
